package com.example.social.screen

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.social.R
import com.example.social.item_view.ThreadItemWithImage
import com.example.social.navigation.Routes
import com.example.social.screen.component.NotThreadList
import com.example.social.utils.SharedPref
import com.example.social.viewmodel.UserViewModel

@Composable
fun OtherUsers(navHostController: NavHostController, uid: String) {
    val context = LocalContext.current

    val currentUserById = SharedPref.getUid(context)

    val userViewModel: UserViewModel = viewModel()
    val threads by userViewModel.threads.observeAsState(emptyList())
    val users by userViewModel.users.observeAsState(null)

    val followerList by userViewModel.followerList.observeAsState(emptyList())
    val followingList by userViewModel.followingList.observeAsState(emptyList())

    val followerIsError by userViewModel.error.observeAsState();
    val followerIsErrorShown by userViewModel.isErrorShown.observeAsState(false)

    //初始化用户数据
    userViewModel.fetchThreads(uid)
    userViewModel.fetchUser(uid)
    users.let {
        userViewModel.getFollowers(users!!.uid)
        userViewModel.getFollowing(users!!.uid)
    }
    // 错误信息弹窗
    LaunchedEffect( followerIsError, followerIsErrorShown) {
        if (!followerIsErrorShown && followerIsError != null) {
            Toast.makeText(context, followerIsError, Toast.LENGTH_SHORT).show()
            userViewModel.markErrorAsShown() // 标记错误信息已显示
        }

    }
    //当前用户监听
    LaunchedEffect(currentUserById) {
        if (currentUserById.isEmpty()) {
            navHostController.navigate(Routes.Login.routes) {
                popUpTo(Routes.Home.routes) { inclusive = true }
                launchSingleTop = true
            }
        }
    }

    LazyColumn {
        item {
            if (users != null) {
                ConstraintLayout(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp, top = 20.dp)
                ) {
                    val (text, logo, userName, bio, followers, following, button) = createRefs()
                    Text(
                        text = users!!.nickName,
                        style = TextStyle(fontWeight = FontWeight.ExtraBold, fontSize = 24.sp),
                        modifier = Modifier
                            .constrainAs(text) {
                                top.linkTo(parent.top)
                                start.linkTo(parent.start)
                            }
                            .padding(start = 15.dp, top = 5.dp)
                    )

                    AsyncImage(
                        model = ImageRequest.Builder(context)
                            .data(users!!.imageurl)
                            .crossfade(true)
                            .error(R.drawable.undraw_male_avatar)
                            .build(),
                        contentDescription = "User Avatar",
                        modifier = Modifier
                            .constrainAs(logo) {
                                top.linkTo(parent.top)
                                end.linkTo(parent.end)
                            }
                            .padding(end = 30.dp, top = 20.dp)
                            .size(120.dp)
                            .clip(CircleShape),
                        contentScale = ContentScale.Crop
                    )

                    Text(
                        text = users!!.nickname!!,
                        style = TextStyle(fontSize = 20.sp),
                        modifier = Modifier
                            .constrainAs(userName) {
                                top.linkTo(text.bottom)
                                start.linkTo(parent.start)
                            }
                            .padding(start = 15.dp, top = 5.dp)
                    )

                    Text(
                        text = users!!.bio,
                        style = TextStyle(fontSize = 14.sp),
                        modifier = Modifier
                            .constrainAs(bio) {
                                top.linkTo(userName.bottom)
                                start.linkTo(parent.start)
                            }
                            .padding(start = 15.dp, top = 5.dp)
                    )

                    Text(
                        text = "粉丝: ${followerList.size}",
                        style = TextStyle(fontSize = 15.sp),
                        modifier = Modifier
                            .constrainAs(followers) {
                                top.linkTo(bio.bottom)
                                start.linkTo(parent.start)
                            }
                            .padding(start = 15.dp, top = 5.dp)
                    )

                    Text(
                        text = "正在关注: ${followingList.size}",
                        style = TextStyle(fontSize = 15.sp),
                        modifier = Modifier
                            .constrainAs(following) {
                                top.linkTo(followers.bottom)
                                start.linkTo(parent.start)
                            }
                            .padding(start = 15.dp, top = 5.dp)
                    )

                    ElevatedButton(onClick = {
                        if (currentUserById.isNotEmpty()) {
                            userViewModel.followUsers(uid, currentUserById)
                        }
                    }, modifier = Modifier
                        .constrainAs(button) {
                            top.linkTo(following.bottom)
                            start.linkTo(parent.start)
                        }
                        .padding(start = 15.dp, top = 10.dp)
                        .clickable {
                            users.let {
                                if (currentUserById == it!!.uid) {
                                    Toast
                                        .makeText(
                                            context,
                                            "你不能关注自己!",
                                            Toast.LENGTH_SHORT
                                        )
                                        .show()
                                } else if (!followerList.contains(currentUserById)) {
                                    userViewModel.followUsers(currentUserById, it.uid)
                                } else {
                                    userViewModel.unfollowUser(currentUserById, it.uid)
                                }
                            }
                        }
                    ) {
                        Text(
                            text = if (followerList.contains(currentUserById)) "取消关注" else "关注Ta"
                        )
                    }
                }
            }
            //下划线
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 10.dp, bottom = 5.dp)
                    .height(2.dp)
                    .background(Color.LightGray) // 自定义颜色
            )
            Text(
                text = "Ta发布的话题", style = TextStyle(
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                ), modifier = Modifier.padding(start = 20.dp)
            )
        }

        if (threads.isNotEmpty()) {
            items(threads) { thread ->
                // 显示包含图片的布局
                ThreadItemWithImage(
                    thread = thread,
                    users = users!!,
                    navHostController = navHostController,
                )
            }
        } else {
            item {
                NotThreadList("该用户暂未发布话题")
            }
        }
    }
}
